package com.neu.fenli2023623.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neu.fenli2023623.entity.Tk;
import com.neu.fenli2023623.service.TkService;
import com.neu.fenli2023623.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/tk")
public class TkController {

    @Autowired
    private TkService tkService;

    //添加备注
    @RequestMapping("AddNote")
    public ResultVo tkUpdate(@RequestBody Tk tk){
        int i = tkService.updateAddNote(tk);
        if (i>0){
            return ResultVo.ok("更新成功");
        }else {
            return ResultVo.ok("更新失败");
        }

    }
//    查询全部
    @RequestMapping("selectall")
    public ResultVo tkSelect() {
        List<Map<String, Object>> tks = tkService.selectAll();
        if (tks != null) {
            // 创建TkResult对象

            // 将TkResult对象转换为JSON格式
            ObjectMapper objectMapper = new ObjectMapper();
            String tkResultJson = null;
            try {
                tkResultJson = objectMapper.writeValueAsString(tks);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return ResultVo.error("转换JSON格式失败");
            }

            // 返回JSON格式数据给前端
            return ResultVo.ok("查找成功").data("tkall",tkResultJson);
        } else {
            return ResultVo.error("查找失败");
        }
    }

    //这里的患者姓名和就诊卡号的参数就用那个输入框里的值传进来，赋一样的值就好,日期可为空
    @RequestMapping("selectByDateRangeOrPatient")
    public ResultVo tkselectByDateRangeOrPatient(@RequestParam String startDate, @RequestParam String endDate,
                                                    @RequestParam("patientName") String patientName,
                                                    @RequestParam("cardNumber") String cardNumber) {
        // 调用Service层方法，根据患者姓名或就诊卡号查询数据
        List<Map<String, Object>> tks = tkService.selectByDateRangeOrPatient(startDate, endDate,patientName, cardNumber);

        if (tks != null) {
            // 将查询结果转换为JSON格式
            ObjectMapper objectMapper = new ObjectMapper();
            String tkResultJson;
            try {
                tkResultJson = objectMapper.writeValueAsString(tks);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return ResultVo.error("转换JSON格式失败");
            }

            // 返回JSON格式数据给前端
            return ResultVo.ok("查询成功").data("ByDateRangeOrPatient",tkResultJson);
        } else {
            return ResultVo.error("查询失败");
        }
    }





}
